package com.example.ivideo_2211a.take

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.common.mvi.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

/**
 * 视频发布ViewModel
 * 管理视频发布的状态和业务逻辑
 */
class VideoPublishViewModel : ViewModel() {
    
    private val repository = VideoPublishRepository()
    
    // 视频录制状态
    private val _recordingState = MutableStateFlow<RecordingState>(RecordingState.Idle)
    val recordingState: StateFlow<RecordingState> = _recordingState.asStateFlow()
    
    // 发布状态
    private val _publishState = MutableStateFlow<PublishState>(PublishState.Idle)
    val publishState: StateFlow<PublishState> = _publishState.asStateFlow()
    
    // 录制的视频文件路径
    private var recordedVideoPath: String? = null
    
    /**
     * 设置录制的视频文件路径
     */
    fun setVideoPath(videoPath: String) {
        recordedVideoPath = videoPath
    }
    
    /**
     * 开始录制视频
     */
    fun startRecording() {
        _recordingState.value = RecordingState.Recording
        // 这里应该调用相机API开始录制
        // 暂时模拟录制过程
    }
    
    /**
     * 停止录制视频
     */
    fun stopRecording() {
        _recordingState.value = RecordingState.Recorded
        // 这里应该停止录制并获取视频文件路径
        // 现在由TakeActivity直接设置路径
    }
    
    /**
     * 发布视频
     */
    fun publishVideo(title: String = "", caption: String = "") {
        if (recordedVideoPath.isNullOrEmpty()) {
            _publishState.value = PublishState.Error("没有录制的视频")
            return
        }
        
        _publishState.value = PublishState.Publishing
        
        viewModelScope.launch {
            try {
                val request = VideoPublishRequest(
                    approved = true,
                    caption = caption,
                    category = "生活",
                    commentCount = 0,
                    likeCount = 0,
                    publishTime = getCurrentTime(),
                    publisherAvatar = "",
                    publisherId = "user_${System.currentTimeMillis()}",
                    tags = "生活,日常",
                    thumbnailUrl = "",
                    title = title.ifEmpty { "我的视频" },
                    videoId = 0,
                    videoUrl = recordedVideoPath!!,
                    viewCount = 0
                )
                
                val result = repository.simplePublishVideo(request)
                
                when (result) {
                    is NetworkResult.Success -> {
                        _publishState.value = PublishState.Success(result.data)
                    }
                    is NetworkResult.Error -> {
                        _publishState.value = PublishState.Error(result.exception.message ?: "发布失败")
                    }
                    is NetworkResult.Loading -> {
                        // 不会到达这里，因为使用的是simpleApiCall
                    }
                }
            } catch (e: Exception) {
                _publishState.value = PublishState.Error(e.message ?: "发布失败")
            }
        }
    }
    
    /**
     * 重置状态
     */
    fun resetState() {
        _recordingState.value = RecordingState.Idle
        _publishState.value = PublishState.Idle
        recordedVideoPath = null
    }
    
    /**
     * 获取当前时间字符串
     */
    private fun getCurrentTime(): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date())
    }
}

/**
 * 录制状态
 */
sealed class RecordingState {
    object Idle : RecordingState()           // 空闲状态
    object Recording : RecordingState()      // 录制中
    object Recorded : RecordingState()       // 录制完成
}

/**
 * 发布状态
 */
sealed class PublishState {
    object Idle : PublishState()             // 空闲状态
    object Publishing : PublishState()       // 发布中
    data class Success(val response: VideoPublishResponse) : PublishState()  // 发布成功
    data class Error(val message: String) : PublishState()  // 发布失败
}
